package com.fadadianqi.mall.web.controller;

import com.fadadianqi.logistics.admin.controller.form.AjaxResult;
import com.fadadianqi.commons.JSONProvider;
import com.fadadianqi.mall.model.Member;
import com.fadadianqi.mall.service.MemberService;
import com.yeqiangwei.commons.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Controller
public class MemberController {

    private static final int LOGIN_TRY_MAX = 5;

    /**
     * 退出系统
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/member/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        String url = ParamUtils.getString(request, "u", "/");
        MemberHelper.del(request, response);
        return "redirect:" + url;
    }


    @RequestMapping("/member/ajax/login/form")
    public String loginForm(HttpServletRequest request, ModelMap modelMap) {
        int err = getErrTotal(request); // 记录第几次登录失败
        Boolean showVcode = HttpSessionUtils.getBoolean(request, "showVcode", Boolean.FALSE);
        if (err >= LOGIN_TRY_MAX) {
            showVcode = Boolean.TRUE;
        } else {
            showVcode = Boolean.FALSE;
        }
        modelMap.put("showVcode", showVcode);
        HttpSessionUtils.setAttribute(request, "showVcode", showVcode);
        return "/member/ajaxLoginForm";
    }

    @RequestMapping("/member/ajax/getMemberInfo")
    public ResponseEntity<String> getMemberInfo(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        AjaxResult rs = new AjaxResult(MemberHelper.getMember(request), Boolean.TRUE, null);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @RequestMapping("/member/ajax/login")
    public ResponseEntity<String> login(HttpServletRequest request
            , HttpServletResponse response
            , ModelMap modelMap) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");

        String id = ParamHelper.getString(request, "i", null);
        String password = ParamHelper.getString(request, "p", null);
        String md5Pwd = StringHelper.MD5(password);
        String vcode = ParamHelper.getString(request, "v", null); // 验证码
        Member member = null;
        Boolean loginSucceed = Boolean.FALSE; // 登录是否成功
        Boolean showVerifyCode = Boolean.FALSE; // 是否显示验证码
        int err = getErrTotal(request); // 记录第几次登录失败
        String errMsg = null;
        if (err >= LOGIN_TRY_MAX) {
            // 判断验证码
            String vcodeSession = getVerifyCodeFromSession(request);
            if (vcode == null || !vcode.equalsIgnoreCase(vcodeSession)) {
                showVerifyCode = Boolean.TRUE;
                // 验证码错误
                String errCode = "exception.member.login.verifyCode.error";
                errMsg = messageSource.getMessage(errCode, null, Locale.getDefault());
                AjaxResult rs = new AjaxResult(showVerifyCode, loginSucceed, errMsg);
                return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                        responseHeaders, HttpStatus.OK);
            }// 验证码正确继续执行
        }
        member = getMember(id);
        if (null == member) {
            errMsg = messageSource.getMessage("exception.member.login.id.notFound", null, Locale.getDefault());
            errAdd(request, response);
        } else if (!md5Pwd.equalsIgnoreCase(member.getPassword())) {
            errMsg = messageSource.getMessage("exception.member.login.password.error", null, Locale.getDefault());
            errAdd(request, response);
        } else {
            // 登录成功 记录session，返回Member对象的json给前端。
            loginSucceed(request, response, member);
            loginSucceed = Boolean.TRUE;
        }
        AjaxResult rs = new AjaxResult(showVerifyCode, loginSucceed, errMsg);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    private String getVerifyCodeFromSession(HttpServletRequest request) {
        return HttpSessionUtils.getString(request, "verifyCode", null);
    }

    @RequestMapping("/member/reg/ajax/verifyCode")
    public ResponseEntity<String> verifyCode(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        Boolean isResponseCorrect = Boolean.FALSE;
        //remenber that we need an id to validate!
        String captchaId = HttpSessionUtils.getString(request, "verifyCode", null);
        //retrieve the response
        String verifyCode = request.getParameter("verifyCode");
        // Call the Service method
        if (captchaId.equalsIgnoreCase(verifyCode)) {
            isResponseCorrect = Boolean.TRUE;
        }
        AjaxResult rs = new AjaxResult(isResponseCorrect, isResponseCorrect, null);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    private Member getMember(String id) {
        Member member = null;
        if (Utils.isMail(id)) {
            member = memberService.getByEmail(id);
        } else if (Utils.isMobileNumber(id)) {
            member = memberService.getByMobile(id);
        } else {
            member = memberService.getByName(id);
        }
        return member;
    }

    private int getErrTotal(HttpServletRequest request) {
        /*String err = HttpCookieUtils.getValue(request, "lerr", null);
		return TypeChange.stringToInt(err, 0);*/
        return HttpSessionUtils.getInteger(request, "lerr", 0);
    }

    private int errAdd(HttpServletRequest request
            , HttpServletResponse response) {
        int i = getErrTotal(request);
        i++;
        //HttpCookieUtils.setValue(response, null, "lerr", i, 360000);
        HttpSessionUtils.setAttribute(request, "lerr", i);
        return i;
    }

    private void errClean(HttpServletRequest request, HttpServletResponse response) {
        //HttpCookieUtils.setValue(response, null, "lerr", "", 360000);
        HttpSessionUtils.setAttribute(request, "lerr", null);
    }

    private void loginSucceed(HttpServletRequest request
            , HttpServletResponse response, Member member) {
        errClean(request, response);
        MemberHelper.save(request, response, member);
    }

    @Autowired
    private MessageSource messageSource;

    @Autowired
    private MemberService memberService;
}
